﻿create procedure [dbo].[usp_ThreadInsert]
	@IsAlive bit
	, @IsBackground bit
	, @IsThreadPoolThread bit
	, @ManagedThreadId int
	, @Name nvarchar(512)
	, @Priority nvarchar(100)
	, @ThreadState nvarchar(100)
	, @CurrentCulture nvarchar(100)
	, @CurrentUICulture nvarchar(100)
as

begin try
	
	begin transaction
	
		if not exists(select * from [dbo].[Thread] where [IsAlive] = @IsAlive and
			                                             [IsBackground] = @IsBackground and 
				                                         ([IsThreadPoolThread] = @IsThreadPoolThread or ([IsThreadPoolThread] is null and @IsThreadPoolThread is null)) and
					                                     [ManagedThreadId] = @ManagedThreadId and
						                                 ([Name] = @Name or ([Name] is null and @Name is null)) and
							                             ([Priority] = @Priority or ([Priority] is null and @Priority is null)) and
							                             [ThreadState] = @ThreadState)
			begin
										                              
				insert [dbo].[Thread]
				(
					[IsAlive]
					, [IsBackground]
					, [IsThreadPoolThread]
					, [ManagedThreadId]
					, [Name]
					, [Priority]
					, [ThreadState]
					, [CurrentCulture]
					, [CurrentUICulture]				
			    )
				values
				(
					@IsAlive
					, @IsBackground
					, @IsThreadPoolThread
					, @ManagedThreadId
					, @Name
					, @Priority
					, @ThreadState
					, @CurrentCulture
					, @CurrentUICulture
				)
				
				select ThreadId, ConcurrencyId, Created, Updated from [dbo].[Thread] where @@rowcount > 0 and ThreadId = scope_identity()
			
			end
			
		else
			
			begin
			
				select ThreadId, ConcurrencyId, Created, Updated from [dbo].[Thread] where [IsAlive] = @IsAlive and
																						   [IsBackground] = @IsBackground and 
																						   ([IsThreadPoolThread] = @IsThreadPoolThread or ([IsThreadPoolThread] is null and @IsThreadPoolThread is null)) and
																						   [ManagedThreadId] = @ManagedThreadId and
																						   ([Name] = @Name or ([Name] is null and @Name is null)) and
																						   ([Priority] = @Priority or ([Priority] is null and @Priority is null)) and
																						   [ThreadState] = @ThreadState
			end
	
	commit transaction

end try
	
begin catch
	if @@trancount > 0
	begin
		rollback transaction;
	end
	execute [dbo].[usp_SqlErrorInsert]
end catch


